/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useRef } from 'react';
import ProForm, {
  ProFormText,
  ProFormList,
  ProFormDigit,
  ProFormMoney,
} from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { deliveryWarning, deliveryCreate } from '@/services/jdk/warn';
import { Space, Form, Button, message, Spin } from 'antd';
import KbAddressSelect from '@/components/KbAddressSelect';

const Index: React.FC = () => {
  const FormItem = Form.Item;
  const [form] = Form.useForm();
  const formRef = useRef<ProFormInstance>();
  const [address, setAddress] = useState<{ province?: string; city?: string; county?: any }>({});
  const [formShow, setFormShow] = useState(false);
  const [loading, setLoading] = useState(false);
  const handleChange = (value: (string | number)[], selectOptions: any[]) => {
    if (!selectOptions.length) {
      setAddress({});
      setFormShow(false);
      return;
    }
    const addressName: string[][] = selectOptions.map((item) => {
      return item.map((item1: any) => item1.label);
    });
    const county = addressName.map((item) => item.slice(2, 3)).flat(Infinity);
    const [province, city] = addressName[0].splice(0, 2);
    setAddress({
      province,
      city,
      county: JSON.stringify(county),
    });
  };
  const handleSearch = () => {
    setLoading(true);
    deliveryWarning(address).then((res) => {
      setLoading(false);
      const { code, data, msg } = res;
      if (code == 0) {
        setFormShow(true);
        formRef.current?.setFieldsValue({ source_config: data });
      } else {
        message.error(msg);
      }
    });
  };
  const resetForm = () => {
    setFormShow(false);
    form.resetFields();
    formRef.current?.setFieldsValue({ source_config: [] });
  };
  const handleSubmit = async (value: any) => {
    setLoading(true);
    const { source_config: source } = value;
    const source_config = JSON.stringify(source);
    deliveryCreate({ ...address, source_config: source_config }).then((res) => {
      const { code, msg } = res;
      setLoading(false);
      if (code == 0) {
        resetForm();
        message.success(msg);
      } else {
        message.error(msg);
      }
    });
  };
  return (
    <Spin spinning={loading}>
      <Space direction='vertical' size='large'>
        <Form onFinish={handleSearch} layout='inline' form={form}>
          <FormItem label='请选择区域' name='address' style={{ width: 350 }}>
            <KbAddressSelect level={2} multiple onChange={handleChange} />
          </FormItem>
          <FormItem>
            <Space direction='horizontal'>
              <Button htmlType='submit' type='primary'>
                查询
              </Button>
              <Button htmlType='reset' onClick={resetForm}>
                重置
              </Button>
            </Space>
          </FormItem>
        </Form>
        {formShow && (
          <ProForm formRef={formRef} submitter={false} onFinish={handleSubmit}>
            <ProFormList name='source_config' actionRender={() => []} creatorButtonProps={false}>
              {() => {
                return (
                  <Space direction='horizontal'>
                    <ProFormText name='source_brand_name' readonly />
                    <ProFormDigit
                      name='limit_kilometre'
                      fieldProps={{
                        precision: 0,
                      }}
                      placeholder='请填写配送距离'
                    />
                    <ProFormText name='source_brand' readonly>
                      公里以内发单费超出
                    </ProFormText>
                    <ProFormMoney
                      name='limit_price'
                      fieldProps={{
                        precision: 2,
                        min: 0,
                      }}
                      customSymbol='¥'
                      placeholder='请填写发单费'
                    />
                    <ProFormText readonly>元，预警提示</ProFormText>
                  </Space>
                );
              }}
            </ProFormList>
            <Button htmlType='submit' type='primary'>
              保存
            </Button>
          </ProForm>
        )}
      </Space>
    </Spin>
  );
};

export default Index;
